<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品类型过滤调试 - 详细版</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
        .container { max-width: 1400px; margin: 0 auto; }
        .section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        .debug-log { background: #f8f9fa; padding: 10px; margin: 10px 0; border-radius: 3px; font-family: monospace; font-size: 12px; max-height: 400px; overflow-y: auto; }
        .controls { display: flex; gap: 10px; align-items: center; margin: 10px 0; }
        select, button, input { padding: 8px; margin: 5px; }
        .product-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 15px; margin-top: 15px; }
        .product-card { border: 1px solid #ddd; padding: 12px; border-radius: 5px; background: #fff; }
        .product-card.highlight { border-color: #007bff; background: #f0f8ff; }
        .loading { color: #666; font-style: italic; }
        .error { color: red; background: #ffe6e6; padding: 10px; border-radius: 3px; }
        .success { color: green; background: #e6f7e6; padding: 5px; border-radius: 3px; }
        .warning { color: orange; background: #fff3cd; padding: 5px; border-radius: 3px; }
        .api-test { background: #e7f3ff; padding: 10px; border-radius: 5px; margin: 10px 0; }
        .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
        .stat-card { background: #f8f9fa; padding: 10px; border-radius: 5px; text-align: center; }
        .type-badge { display: inline-block; background: #6c757d; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px; margin: 2px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 产品类型过滤调试工具</h1>
        
        <div class="section">
            <h2>🎛️ 控制面板</h2>
            <div class="controls">
                <label>产品类型: </label>
                <select id="productTypeSelect">
                    <option value="">全部类型</option>
                </select>
                <button onclick="loadProducts()">手动刷新</button>
                <button onclick="testAllFilters()">测试所有过滤器</button>
                <button onclick="clearLog()">清空日志</button>
                <button onclick="exportData()">导出数据</button>
            </div>
            
            <div class="controls">
                <label>测试URL: </label>
                <input type="text" id="testUrl" placeholder="手动输入API URL测试" style="width: 400px;">
                <button onclick="testCustomUrl()">测试自定义URL</button>
            </div>
            
            <div class="stats" id="stats">
                <div class="stat-card">
                    <h4>产品类型总数</h4>
                    <div id="totalTypes">-</div>
                </div>
                <div class="stat-card">
                    <h4>产品总数</h4>
                    <div id="totalProducts">-</div>
                </div>
                <div class="stat-card">
                    <h4>过滤后产品数</h4>
                    <div id="filteredCount">-</div>
                </div>
                <div class="stat-card">
                    <h4>当前选择</h4>
                    <div id="currentFilter">全部类型</div>
                </div>
            </div>
        </div>

        <div class="section">
            <h2>📊 API测试结果</h2>
            <div id="apiTestResults" class="api-test">
                等待测试...
            </div>
        </div>

        <div class="section">
            <h2>📋 调试日志</h2>
            <div id="debugLog" class="debug-log">
                [系统] 调试工具已启动
            </div>
        </div>

        <div class="section">
            <h2>📦 产品列表</h2>
            <div id="productList" class="product-grid">
                <div class="loading">正在加载...</div>
            </div>
        </div>
    </div>

    <script>
        let productTypes = [];
        let allProducts = [];
        let currentProductTypeRef = '';
        
        function log(message, type = 'info') {
            const debugLog = document.getElementById('debugLog');
            const timestamp = new Date().toLocaleTimeString();
            const colors = {
                'info': '#333',
                'success': '#28a745',
                'warning': '#ffc107',
                'error': '#dc3545'
            };
            
            debugLog.innerHTML += `<div style="color: ${colors[type]}">[${timestamp}] ${message}</div>`;
            debugLog.scrollTop = debugLog.scrollHeight;
            console.log(`[${timestamp}] ${message}`);
        }

        function clearLog() {
            document.getElementById('debugLog').innerHTML = '[系统] 日志已清空';
        }

        async function loadProductTypes() {
            try {
                log('🔄 正在加载产品类型...', 'info');
                const response = await fetch('/apis/content.halo.run/v1alpha1/product-types');
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                productTypes = data.items || [];
                
                log(`✅ 成功加载 ${productTypes.length} 个产品类型`, 'success');
                
                // 更新统计
                document.getElementById('totalTypes').textContent = productTypes.length;
                
                // 填充下拉框
                const select = document.getElementById('productTypeSelect');
                select.innerHTML = '<option value="">全部类型</option>';
                
                productTypes.forEach(type => {
                    const option = document.createElement('option');
                    option.value = type.metadata.name;
                    option.textContent = `${type.spec.displayName} (${type.metadata.name})`;
                    select.appendChild(option);
                });
                
                log(`📋 产品类型详情: ${productTypes.map(t => `${t.spec.displayName}(${t.metadata.name})`).join(', ')}`, 'info');
                
                return productTypes;
                
            } catch (error) {
                log(`❌ 加载产品类型失败: ${error.message}`, 'error');
                throw error;
            }
        }

        async function loadProducts(productTypeRef = '') {
            try {
                currentProductTypeRef = productTypeRef;
                
                // 构建API URL
                let apiUrl = '/apis/content.halo.run/v1alpha1/products?page=1&size=100';
                if (productTypeRef) {
                    apiUrl += `&productTypeRef=${encodeURIComponent(productTypeRef)}`;
                }
                
                log(`🔄 正在调用API: ${apiUrl}`, 'info');
                document.getElementById('currentFilter').textContent = productTypeRef || '全部类型';
                
                // 显示加载状态
                document.getElementById('productList').innerHTML = '<div class="loading">正在加载产品...</div>';
                
                const response = await fetch(apiUrl);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                allProducts = data.items || [];
                
                log(`✅ API返回 ${allProducts.length} 个产品`, 'success');
                
                // 更新统计
                document.getElementById('totalProducts').textContent = data.total || allProducts.length;
                document.getElementById('filteredCount').textContent = allProducts.length;
                
                // 分析产品类型分布
                const typeDistribution = {};
                allProducts.forEach(product => {
                    const typeRef = product.spec.productTypeRef || 'null';
                    typeDistribution[typeRef] = (typeDistribution[typeRef] || 0) + 1;
                });
                
                log(`📊 产品类型分布: ${JSON.stringify(typeDistribution)}`, 'info');
                
                // 检查过滤效果
                if (productTypeRef) {
                    const matchingProducts = allProducts.filter(p => p.spec.productTypeRef === productTypeRef);
                    const wrongProducts = allProducts.filter(p => p.spec.productTypeRef !== productTypeRef);
                    
                    if (wrongProducts.length > 0) {
                        log(`⚠️ 过滤异常: 期望只返回类型为 "${productTypeRef}" 的产品，但发现 ${wrongProducts.length} 个其他类型产品`, 'warning');
                        log(`异常产品: ${wrongProducts.map(p => `${p.spec.displayName}(${p.spec.productTypeRef})`).join(', ')}`, 'warning');
                    } else {
                        log(`✅ 过滤正确: 所有 ${matchingProducts.length} 个产品都属于类型 "${productTypeRef}"`, 'success');
                    }
                } else {
                    log(`📋 显示全部产品: ${allProducts.length} 个产品`, 'info');
                }
                
                displayProducts(allProducts);
                updateApiTestResults(apiUrl, data);
                
            } catch (error) {
                log(`❌ 加载产品失败: ${error.message}`, 'error');
                document.getElementById('productList').innerHTML = `<div class="error">加载失败: ${error.message}</div>`;
            }
        }

        function displayProducts(products) {
            const container = document.getElementById('productList');
            
            if (products.length === 0) {
                container.innerHTML = '<div class="warning">没有找到产品</div>';
                return;
            }
            
            container.innerHTML = products.map(product => {
                const isHighlight = currentProductTypeRef && product.spec.productTypeRef === currentProductTypeRef;
                const typeName = getProductTypeName(product.spec.productTypeRef);
                
                return `
                    <div class="product-card ${isHighlight ? 'highlight' : ''}">
                        <h4>${product.spec.displayName}</h4>
                        <div class="type-badge">${typeName}</div>
                        <p><strong>类型引用:</strong> <code>${product.spec.productTypeRef}</code></p>
                        <p><strong>价格:</strong> ${formatPrice(product.spec.price)}</p>
                        <p><strong>状态:</strong> ${product.spec.published ? '✅ 已发布' : '❌ 未发布'}</p>
                        <p><strong>描述:</strong> ${product.spec.description || '无描述'}</p>
                        <small><strong>ID:</strong> <code>${product.metadata.name}</code></small>
                    </div>
                `;
            }).join('');
        }

        function getProductTypeName(productTypeRef) {
            const productType = productTypes.find(type => type.metadata.name === productTypeRef);
            return productType ? productType.spec.displayName : productTypeRef || '未知类型';
        }

        function formatPrice(price) {
            if (price === undefined || price === null) return '-';
            return `¥${price.toFixed(2)}`;
        }

        function updateApiTestResults(url, data) {
            const container = document.getElementById('apiTestResults');
            container.innerHTML = `
                <h4>最后一次API调用</h4>
                <p><strong>URL:</strong> <code>${url}</code></p>
                <p><strong>返回状态:</strong> <span class="success">成功</span></p>
                <p><strong>返回数据量:</strong> ${data.items?.length || 0} 个产品</p>
                <p><strong>总数:</strong> ${data.total || 'N/A'}</p>
                <p><strong>页码:</strong> ${data.page || 1}</p>
                <p><strong>页大小:</strong> ${data.size || 'N/A'}</p>
                <details>
                    <summary>查看完整响应</summary>
                    <pre>${JSON.stringify(data, null, 2)}</pre>
                </details>
            `;
        }

        async function testAllFilters() {
            log('🧪 开始测试所有过滤器...', 'info');
            
            try {
                // 测试全部类型
                log('测试1: 全部类型过滤', 'info');
                await loadProducts('');
                await new Promise(resolve => setTimeout(resolve, 1000));
                
                // 测试每个产品类型
                for (let i = 0; i < productTypes.length; i++) {
                    const productType = productTypes[i];
                    log(`测试${i + 2}: 产品类型 "${productType.spec.displayName}" (${productType.metadata.name})`, 'info');
                    await loadProducts(productType.metadata.name);
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
                
                log('✅ 所有过滤器测试完成', 'success');
                
            } catch (error) {
                log(`❌ 过滤器测试失败: ${error.message}`, 'error');
            }
        }

        async function testCustomUrl() {
            const url = document.getElementById('testUrl').value;
            if (!url) {
                log('⚠️ 请输入要测试的URL', 'warning');
                return;
            }
            
            try {
                log(`🔗 测试自定义URL: ${url}`, 'info');
                const response = await fetch(url);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                log(`✅ 自定义URL测试成功，返回 ${data.items?.length || 0} 个产品`, 'success');
                
                allProducts = data.items || [];
                displayProducts(allProducts);
                updateApiTestResults(url, data);
                
            } catch (error) {
                log(`❌ 自定义URL测试失败: ${error.message}`, 'error');
            }
        }

        function exportData() {
            const exportData = {
                timestamp: new Date().toISOString(),
                productTypes: productTypes,
                allProducts: allProducts,
                currentFilter: currentProductTypeRef,
                logs: document.getElementById('debugLog').innerHTML
            };
            
            const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `product-filter-debug-${Date.now()}.json`;
            a.click();
            URL.revokeObjectURL(url);
            
            log('📁 调试数据已导出', 'success');
        }

        // 监听下拉框变化
        document.getElementById('productTypeSelect').addEventListener('change', function() {
            const selectedType = this.value;
            log(`🎯 用户选择产品类型: ${selectedType || '全部类型'}`, 'info');
            loadProducts(selectedType);
        });

        // 初始化
        document.addEventListener('DOMContentLoaded', async function() {
            log('🚀 调试工具初始化中...', 'info');
            
            try {
                await loadProductTypes();
                await loadProducts('');
                log('✅ 初始化完成', 'success');
            } catch (error) {
                log(`❌ 初始化失败: ${error.message}`, 'error');
            }
        });
    </script>
</body>
</html>